<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>耀耀学院_test01_单个表单项的处理</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        div{
            width: 350px;
            height: auto;
            margin: 20px;
        }
        div input{
            width: 250px;
            height: 28px;
            border-radius: 4px;
            border: 1px solid grey;
        }
        p{
            margin-left: 37px;
            color: grey;
            font-size: 14px;
            margin-top: 7px;
        }
        pwrong{
        }
        label{
            font-weight: bold;
        }
        button{
            width: 45px;
            height: 28px;
            border-radius: 4px;
            background-color: #0d58ff;
            border: 1px solid transparent;
            color: #ffffff;
        }
        .right{
            border: 1px solid #48805a;
        }
        .error{
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <div>
    <label>名称 </label>
    <input type="text" id="input_text">
    <button>验证</button>
    <p>必填,长度为4~16个字符</p>
    </div>
<script>

    function getLength() {
        var text=document.getElementById("input_text").value;
        var enlen=0,zhlen=0;
        for(var i=0;i<text.length;i++){
            if(text.charCodeAt(i)>255)
            {
                zhlen+=2;
            }
            else
                    enlen++;
        }
        return enlen+zhlen;
    }
    function check(len) {
        var p=document.getElementsByTagName("p")[0];
        if(len==0)
        {
            p.innerHTML="名称不能为空";
            document.getElementById("input_text").className="error";
            p.style.color="red";
        }
        else if(len<4||len>16)
        {
            p.innerHTML="长度范围需在4~16";
            document.getElementById("input_text").className="error";
            p.style.color="red";
        }
        else
        {
            p.innerHTML="名称格式正确";
            document.getElementById("input_text").className="right";
            p.style.color="green";
        }

    }

    document.getElementsByTagName("button")[0].onclick=function () {
        var len= getLength();
       check(len);
    };
</script>
</body>
</html>